package com.ruirui.controller;

import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;

import javax.print.attribute.standard.Media;
import javax.print.attribute.standard.MediaTray;
import java.net.URI;
import java.time.Duration;
import java.util.Map;

@RestController
public class FluxController {


    /**
     * 这是 Spring WebFlux 或 Spring MVC 中用于
     * 推送式数据流（SSE） 的响应类型，
     * 常用于服务端向浏览器 实时推送数据（如聊天消息、实时监控、股票价格等）。
     *
     * @return
     */
    @GetMapping(value = "/test", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> test() {
        return Flux.just("1", "2", "3")
                .delayElements(Duration.ofMillis(1000)).log();
        //
    }

    @GetMapping(value = "/sse", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ServerSentEvent<String>> sse() {

        return Flux.range(1, 20)
                .map(i -> ServerSentEvent.builder("")
                        .data(i + "")
                        .comment("hh")
                        .build())
                .delayElements(Duration.ofMillis(1000));
    }

    @GetMapping(value = "/sse2", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ServerSentEvent<String>> sse2(ServerWebExchange webExchange) {
        // ServerWebExchange 是 Spring WebFlux 中用于处理 HTTP 请求和响应的接口。
        // 文件上传@RequestPart
        return Flux.range(1, 20)
                .map(i -> ServerSentEvent.builder("")
                        .data(i + "")
                        .comment("hh")
                        .build())
                .delayElements(Duration.ofMillis(1000));

    }

}

